//
//  HMStatusListViewModel.swift
//  weibo
//
//  Created by LCH on 16/3/10.
//  Copyright © 2016年 lch. All rights reserved.
//

import UIKit
import SDWebImage

class HMStatusListViewModel: NSObject {
    
    var statusArray: [HMStatusViewModel]?
    // TODO:判断上拉加载的逻辑
    func loadData(isPullUp:Bool,finish:(isSuccess:Bool)->()) {
        
        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
        
        var maxId:Int64 = 0
        if isPullUp {
        
         maxId = statusArray?.last?.status?.id ?? 0
            
            if maxId != 0{
             
              maxId--
            }
        
        }
        
        let parameters = [
            
            "access_token": HMUserAccountViewModel.sharedAccountViewModel.accessToken!,
            "max_id": "\(maxId)"
        ]
        
        HMNetworkTools.sharedTools.requst(.GET, urlString: url, parameters: parameters) { (responseObject, error) -> () in
            if error != nil {
                
                print("数据请求错误")
                finish(isSuccess: false)
                return
                
            }
//            print("\(responseObject)")
            
            let dicts = responseObject!["statuses"] as! [[String:AnyObject]]
            
            var tempArray = [HMStatusViewModel]()
            
            for dict in dicts {
                
                let status = HMStatus(dict:dict)
               
                if status.pic_urls?.count != 0{
                
//                  print("呵呵")
                }
//                tempArray.append(status)
                
                let viewModel = HMStatusViewModel(status: status)
                tempArray.append(viewModel)
                
                if self.statusArray == nil {
                  
                  self.statusArray = [HMStatusViewModel]()
                }
                
            }
//            self.statusArray = tempArray
            
            self.statusArray! = self.statusArray! + tempArray
        
//            finish(isSuccess: true)
//            self.tableView.reloadData()
            
            self.cacheSingleIage(tempArray,finish:finish)
            
        }
        
        }
    
    private func cacheSingleIage(viewModels:[HMStatusViewModel],finish:(isSuccess:Bool)->()) {
    
      let group = dispatch_group_create()
      let queue = dispatch_get_main_queue()
        
        for viewModel in viewModels {
        
         var urls = viewModel.status?.pic_urls
//         print("urls = \(urls)")
            if urls == nil || urls!.count == 0 {
            
             urls = viewModel.status?.retweeted_status?.pic_urls
            
            }
            if urls?.count == 1 {
            
                guard let urlString = urls?.first?.thumbnail_pic else {
                
                continue
                }
                
            dispatch_group_enter(group)
                
            SDWebImageManager.sharedManager().downloadImageWithURL(NSURL(string: urlString), options: [], progress: nil, completed: { (image, error, _, _, url) -> Void in
                
//                  print("下载完成,地址是:\(url.absoluteString)")
                
                dispatch_group_leave(group)
                })
            
            }
            
            
        
        }
      dispatch_group_notify(group, queue) { () -> Void in
        
        print("所有单张图片下载完成")
        
        finish(isSuccess: true)
        }
    
    }
    

}
